<template>
  <div class="workorder-form">
    <el-card>
      <h2>{{ isEdit ? '编辑工单' : '新增工单' }}</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="max-width:500px;">
        <el-form-item label="工单编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择客户" style="width: 100%;">
            <el-option
              v-for="customer in customers"
              :key="customer.customerId"
              :label="customer.customerName"
              :value="customer.customerId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务" prop="businessId">
          <el-select v-model="form.businessId" placeholder="请选择业务" style="width: 100%;">
            <el-option
              v-for="business in businesses"
              :key="business.businessId"
              :label="business.businessName"
              :value="business.businessId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人员" prop="assignedTo">
          <el-select v-model="form.assignedTo" placeholder="请选择处理人员" style="width: 100%;">
            <el-option
              v-for="staff in staffs"
              :key="staff.staffId"
              :label="staff.realName"
              :value="staff.staffId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority">
            <el-option :value="1" label="高" />
            <el-option :value="2" label="中" />
            <el-option :value="3" label="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="orderStatus">
          <el-select v-model="form.orderStatus">
            <el-option :value="0" label="新建" />
            <el-option :value="1" label="处理中" />
            <el-option :value="2" label="已完成" />
            <el-option :value="3" label="已退回" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addWorkorder, updateWorkorder, getWorkorder } from '@/api/workorder'
import { getCustomers } from '@/api/customer'
import { getBusinesses } from '@/api/business'
import { getStaffs } from '@/api/staff'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const isEdit = ref(false)

// 表单数据
const form = ref({
  orderNumber: '',
  customerId: null,
  businessId: null,
  assignedTo: null,
  description: '',
  priority: 2,
  orderStatus: 0,
  remark: ''
})

// 下拉选项数据
const customers = ref([])
const businesses = ref([])
const staffs = ref([])

// 表单验证规则
const rules = {
  orderNumber: [{ required: true, message: '请输入工单编号', trigger: 'blur' }],
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  businessId: [{ required: true, message: '请选择业务', trigger: 'change' }],
  assignedTo: [{ required: true, message: '请选择处理人员', trigger: 'change' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
}

// 加载下拉选项数据
const loadOptions = async () => {
  try {
    // 加载客户列表
    const customerRes = await getCustomers({ limit: 1000 })
    customers.value = customerRes.records || customerRes || []
    
    // 加载业务列表
    const businessRes = await getBusinesses({ limit: 1000 })
    businesses.value = businessRes.records || businessRes || []
    
    // 加载员工列表
    const staffRes = await getStaffs({ limit: 1000 })
    staffs.value = staffRes.records || staffRes || []
  } catch (error) {
    console.error('加载选项数据失败:', error)
    ElMessage.error('加载选项数据失败')
  }
}

onMounted(async () => {
  await loadOptions()
  
  if (route.params.id) {
    isEdit.value = true
    try {
      const res = await getWorkorder(route.params.id)
      Object.assign(form.value, res)
    } catch (error) {
      console.error('获取工单详情失败:', error)
      ElMessage.error('获取工单详情失败')
    }
  }
})

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      const res = await updateWorkorder(form.value)
      if (res.success) {
        ElMessage.success(res.message || '修改成功')
        router.push('/workorders')
      } else {
        ElMessage.error(res.message || '修改失败')
      }
    } else {
      const res = await addWorkorder(form.value)
      if (res.success) {
        ElMessage.success(res.message || '新增成功')
        router.push('/workorders')
      } else {
        ElMessage.error(res.message || '新增失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

const goBack = () => router.push('/workorders')
</script>

<style scoped>
.workorder-form {
  padding: 32px 0;
}
</style>